package org.adream.account.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.adream.account.service.ADreamServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.utils.encoder.BASE64Decoder;
import com.cloopen.rest.sdk.utils.encoder.BASE64Encoder;
import com.google.common.base.Splitter;
import com.tencentcloudapi.cms.v20190321.CmsClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class Utils {

	private static final Logger logger = LoggerFactory.getLogger(Utils.class);
	
	//认证角色顺序——认证角色
	private final static Map<Integer, String> roleSortMap = new HashMap<>();
	
	//五星角色——五星名称
	public final static Map<String, String> starRleIdRleNameMap = new HashMap<>();
	
	static {
		roleSortMap.put(Constant.TEACHER_SORT, Constant.TEACHER_ROLE_ID);
		roleSortMap.put(Constant.VOL_SORT, Constant.VOL_ROLE_ID);
		roleSortMap.put(Constant.COACH_PLAN_SORT, Constant.COACH_PLAN_ROLE_ID);
		roleSortMap.put(Constant.BUSINESS_SORT, Constant.BUSINESS_ROLE_ID);
		roleSortMap.put(Constant.GOV_SORT, Constant.GOV_ROLE_ID);
		roleSortMap.put(Constant.ORG_SORT, Constant.ORG_ROLE_ID);
		roleSortMap.put(Constant.SPECIAL_FUND_SORT, Constant.SPECIAL_FUND_ROLE_ID);
		
		roleSortMap.put(Constant.PUBLIC_WELFARE_TEAM_SORT, Constant.PUBLIC_WELFARE_TEAM_ROLE_ID);
		roleSortMap.put(Constant.ADREAM_CENTER_SORT, Constant.ADREAM_CENTER_ROLE_ID); 
		roleSortMap.put(Constant.STUDENT_SORT, Constant.STUDENT_ROLE_ID); 
		
		roleSortMap.put(Constant.ADREAM_CENTER_SORT_C, Constant.ADREAM_CENTER_C_ROLE_ID); 
		
		roleSortMap.put(Constant.GFA_TEACHER_SORT, Constant.GFA_TEACHER_ID);
		roleSortMap.put(Constant.GFA_STUDENT_SORT, Constant.GFA_STUDENT_ID);
		roleSortMap.put(Constant.GFA_VOL_A_SORT, Constant.GFA_VOL_A_ID);
		roleSortMap.put(Constant.GFA_VOL_B_SORT, Constant.GFA_VOL_B_ID);
		
		roleSortMap.put(Constant.COACH_PLAN_A_SORT,Constant.COACH_PLAN_A_ID);
		roleSortMap.put(Constant.COACH_PLAN_B_SORT,Constant.COACH_PLAN_B_ID);
		roleSortMap.put(Constant.COACH_PLAN_C_SORT,Constant.COACH_PLAN_C_ID);
		roleSortMap.put(Constant.COACH_PLAN_D_SORT,Constant.COACH_PLAN_D_ID);
		
		roleSortMap.put(Constant.HTC_H_SORT,Constant.HTC_H_ID);
		roleSortMap.put(Constant.EXCELLENCE_ADREAM_HEAD_MASTER_ENROLL_SORT,Constant.EXCELLENCE_ADREAM_HEAD_MASTER_ENROLL_ROLE_ID);
		
		starRleIdRleNameMap.put(Constant.ONE_STAR_ADREAM_ROLE_ID, "一星");
		starRleIdRleNameMap.put(Constant.TWO_STAR_ADREAM_ROLE_ID, "二星");
		starRleIdRleNameMap.put(Constant.THREE_STAR_ADREAM_ROLE_ID, "三星");
		starRleIdRleNameMap.put(Constant.FOUR_STAR_ADREAM_ROLE_ID, "四星");
		starRleIdRleNameMap.put(Constant.FIVE_STAR_ADREAM_ROLE_ID, "五星");
	}

	/**
	 * 获取为空的属性名称
	 * 
	 * @param source
	 *            源对象
	 * @return
	 */
	public static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null) {
				emptyNames.add(pd.getName());
			}
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	/**
	 * 忽略空值拷贝属性值时
	 * 
	 * @param src
	 *            源对象
	 * @param target
	 *            目标对象
	 */
	public static void copyPropertiesIgnoreNull(Object src, Object target) {
		BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
	}

	public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
			"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8",
			"9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
			"U", "V", "W", "X", "Y", "Z" };

	public static String[] numChars = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

	public static String[] letters = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
			"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H",
			"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

	/**
	 * 获取六位的uuid
	 * 
	 * @return
	 */
	public static String getSixUuid() {
		StringBuffer stringBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 6; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int strInteger = Integer.parseInt(str, 16);
			stringBuffer.append(chars[strInteger % 0x3E]);
		}
		return stringBuffer.toString();
	}

	/**
	 * 获取6位授权码随机字符串 前2位英文 后4位数字
	 * 
	 * @return
	 */
	public static String getAuthorizationCode() {
		StringBuffer stringBuffer = new StringBuffer();
		Random rd = new Random();
		for (int k = 0; k < 6; k++) {
			int index = 0;
			if (k < 2) {
				index = rd.nextInt(letters.length);
				stringBuffer.append(letters[index]);
			} else {
				index = rd.nextInt(numChars.length);
				stringBuffer.append(numChars[index]);
			}
		}
		return stringBuffer.toString();
	}
	/**
	 * 获取16位qr随机字符串
	 * 
	 * @return
	 */
	public static String getQrCode() {
		StringBuffer stringBuffer = new StringBuffer();
		Random rd = new Random();
		for (int k = 0; k < 16; k++) {
			int index = 0;
			index = rd.nextInt(chars.length);
			stringBuffer.append(chars[index]);
		}
		return stringBuffer.toString();
	}
	/**
	 * 时间格式 ——>字符串
	 * 
	 * @return
	 */
	public static String Date2String() {
		DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String time = sdf.format(date);
		return time;
	}

	/**
	 * 检测图片是否为url
	 * 
	 * @param imgName
	 *            图片名称
	 * @return
	 */
	public static boolean isContainExt(String imgName) {
		if (StringUtils.isEmpty(imgName)) {
			return false;
		}
		boolean isContainExt = false;
		String[] imgExts = Constant.imgExts;
		for (String imgExt : imgExts) {
			if (imgName.toLowerCase().endsWith(imgExt)) {
				isContainExt = true;
				break;
			}
		}
		return isContainExt;
	}

	/**
	 * 获取4位随机数字字符串
	 * 		不足4位用0补全
	 * @return
	 */
	public static String getNumString() {
		Random r = new Random();
		String num = r.nextInt(9999) + "";
		StringBuffer sb = new StringBuffer();
		int length = num.length();
		for (int i = 0; i < 4 - length; i++) {
			sb.append("0");
		}
		num = sb.toString() + num;
		return num;
	}

	/**
	 * 获取文件名称,及存放路径
	 * 
	 * @param file
	 * @param filePath
	 * @return
	 */
	public static String[] getFileName(MultipartFile file, String filePath) {
		String path = filePath.endsWith(File.separator) ? filePath : filePath + File.separator;
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		String oriFileName = file.getOriginalFilename();
		String ext = oriFileName.substring(oriFileName.lastIndexOf(".") + 1);
		if(StringUtils.isEmpty(ext)) {
			ext = "jpg";
		}
		String fileName = parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
		String[] fileNameArray = { path, fileName };
		return fileNameArray;
	}

	/**
	 * 处理图片文件
	 * 
	 * @param pic
	 * @param picPath
	 * @return
	 */
	public static String[] dealPicFile(MultipartFile pic, String picPath) {
		String[] picArray;
		String oriFileName = pic.getOriginalFilename();
		if (isContainExt(oriFileName)) { // 判断是否为url
			picArray = getFileName(pic, picPath);
		} else {
			picArray = new String[] { oriFileName };
		}
		return picArray;
	}

	/**
	 * base64转为图片
	 * 
	 * @param base64url
	 * @param path
	 *            路径 + 文件名
	 * @return
	 */
	public static boolean generateImage(String base64url, String path) {
		if (base64url == null)
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			// 解密
			// 处理数据
			byte[] b = decoder.decodeBuffer(base64url.substring(base64url.indexOf(",") + 1));
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			out = new FileOutputStream(path);
			out.write(b);
			out.flush();
			return true;
		} catch (Exception e) {
			logger.error("生成图片出错:" + e.getMessage());
			return false;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error("io异常:(");
				}
			}
		}
	}

	/**
	 * 裁剪图片
	 * 
	 * @param filePath
	 * @param x
	 * @param y
	 * @param w
	 *            width
	 * @param h
	 *            height
	 */
	public static boolean cutImage(String filePath, int x, int y, int width, int height) {
		// 首先通过ImageIo中的方法,创建一个Image + InputStream到内存
		ImageInputStream iis = null;
		try {
			iis = ImageIO.createImageInputStream(new FileInputStream(filePath));
			String ext = getFileExt(filePath);
			if (StringUtils.isEmpty(ext)) {
				logger.error("图片裁剪失败:文件格式有误:(");
				return false;
			}
			// 再按照指定格式构造一个Reader(Reader不能new的)
			Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(ext);
			ImageReader imagereader = it.next();
			// 再通过ImageReader绑定 InputStream
			imagereader.setInput(iis);

			// 设置感兴趣的源区域。
			ImageReadParam param = imagereader.getDefaultReadParam();
			param.setSourceRegion(new Rectangle(x, y, width, height));
			// 从 reader得到BufferImage
			BufferedImage bi = imagereader.read(0, param);

			// 将BuffeerImage写出通过ImageIO
			return ImageIO.write(bi, ext, new File(filePath));
		} catch (IOException e) {
			logger.error("图片裁剪失败:" + e.getMessage());
			return false;
		} finally {
			try {
				if (iis != null) {
					iis.close();
				}
			} catch (IOException e) {
				logger.error("裁剪图片出现错误:" + e.getMessage());
			}
		}
	}

	/**
	 * 数据用星号替换
	 * 
	 * @param data
	 *            数据
	 * @param frontLen
	 *            前面位数
	 * @param endLen
	 *            后面位数
	 * @return
	 */
	public static String replaceXing(String data, int frontLen, int endLen) {
		if (StringUtils.isEmpty(data)) {
			return data;
		}
		int length = data.length();
		int len = (frontLen + endLen) >= length ? length : length - frontLen - endLen;

		String xing = "";
		for (int i = 0; i < len; i++) {
			xing += '*';
		}
		if (len == length) {
			return xing;
		} else {
			return data.substring(0, frontLen) + xing + data.substring(data.length() - endLen);
		}
	}

	/**
	 * 时间解析为年月日格式
	 * 
	 * @param date
	 * @return
	 */
	public static String parseDateToYearMonthDay(Date date) {
		// 获取默认选中的日期的年月日星期的值，并赋值
		Calendar calendar = Calendar.getInstance();// 日历对象
		calendar.setTime(date);// 设置当前日期

		String year = calendar.get(Calendar.YEAR) + "";// 获取年份
		int m = calendar.get(Calendar.MONTH) + 1;// 获取月份
		String month = m < 10 ? "0" + m : m + "";
		int d = calendar.get(Calendar.DATE);// 获取日
		String day = d < 10 ? "0" + d : d + "";
		return year + month + day;
	}

	/**
	 * 隐藏邮箱地址,只显示@前面的首位和末位
	 * 
	 * @param email
	 *            邮箱地址 $1，$2分别匹配第一个括号和第二个括号中的内容
	 * @return
	 */
	public static String hideEmail(String email) {
		return (email == null) ? null : email.replaceAll("(\\w?)(\\w*)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4");
	}

	/**
	 * 读取图片内容,获取文件后缀名
	 * 
	 * @param path
	 *            文件路径
	 * @return
	 * @throws IOException
	 */
	public static String getFileExt(String path) {
		String ext = "";
		String hex = "";
		if (path != null) {
			File image = new File(path);
			InputStream is = null;
			try {
				is = new FileInputStream(image);
				byte[] bt = new byte[2];
				is.read(bt);
				hex = bytesToHexString(bt);
			} catch (FileNotFoundException e) {
				logger.error("io异常,文件未找到:(");
			} catch (IOException e) {
				logger.error("io异常:" + e.getMessage());
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						logger.error("io异常:" + e.getMessage());
					}
				}
			}
			if (Constant.JPG_JPEG_HEX.equals(hex)) {
				ext = "jpg";
			} else if (Constant.GIF_HEX.equals(hex)) {
				ext = "gif";
			} else if (Constant.PNG_HEX.equals(hex)) {
				ext = "png";
			}
		}
		return ext;
	}

	/**
	 * byte——>>>hex字符串
	 * 
	 * @param src
	 * @return
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 验证手机有效性
	 * @param phone	手机号
	 * @return
	 */
	public static boolean verifyPhone(String phone) {
//		Pattern p = Pattern.compile("^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-9]))[0-9]{8}$");
		Pattern  p = Pattern.compile("^[1][0-9]{10}$");
		if (StringUtils.isEmpty(phone)) {
			return false;
		} else {
			return p.matcher(phone).matches();
		}
	}

	/**
	 * 验证邮箱地址有效性
	 * @param email	邮箱地址
	 * @return
	 */
	public static boolean verifyEmail(String email) {
		Pattern p = Pattern.compile("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
		if (StringUtils.isEmpty(email)) {
			return false;
		} else {
			return p.matcher(email).matches();
		}
	}

	/**
	 * 判断Collection是否为null或[]
	 * 
	 * @param collection
	 * @return
	 */
	public static boolean isEmptyCollection(Collection<?> collection) {
		return collection == null || collection.isEmpty();
	}

	/**
	 * 按比例压缩图片
	 * 
	 * @param in
	 * @param scale
	 *            压缩比例
	 * @param desPic
	 *            目标图片
	 * @throws IOException
	 */
	public static boolean compress(InputStream in, float scale, String desPic) {
		try {
			logger.debug("按比例压缩图片");
			Thumbnails.of(in).scale(scale).toFile(desPic);
			return true;
		} catch (IOException e) {
			logger.warn("图片压缩失败:" + e.getMessage());
			return false;
		}
	}
	
	/**
	 * 按比例压缩图片并添加按比例水印图片
	 * @param in
	 * 				inputstream
	 * @param scale
	 * 				压缩比例
	 * @param watermark
	 * 				水印图片
	 * @param desPic
	 * 				目标图片
	 * @return
	 */
	public static boolean compressWatermark(InputStream in, float scale, String watermark, String desPic) {
		OutputStream out = null;
		try {
			logger.debug("按比例压缩图片并添加水印");
			Thumbnails.of(in).scale(scale).toFile(desPic);	//压缩图片
			
			Image srcImg = ImageIO.read(new File(desPic));
			BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
			int srcWidth = srcImg.getWidth(null);
			int srcHeight = srcImg.getHeight(null);
			
			// 1、得到画笔对象
			Graphics2D g = buffImg.createGraphics();

			// 2、设置对线段的锯齿状边缘处理
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g.drawImage(srcImg.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH), 0, 0, null);

			// 3、设置水印旋转
//			if (null != degree) {
//				g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
//			}
			
			// 4、水印图片的路径 水印图片一般为gif或者png的，这样可设置透明度
			ImageIcon imgIcon = new ImageIcon(watermark);

			// 5、得到Image对象。
			Image img = imgIcon.getImage();
			int watermarkImageWidth = img.getWidth(null);
			int watermarkImageHeight = img.getHeight(null);
			double dmarkWidth = srcWidth * 0.2;// 设置水印的宽度为图片宽度的0.2倍
			double dmarkHeight = dmarkWidth * ((double) watermarkImageHeight / (double) watermarkImageWidth);// 强转为double计算宽高比例
			int imarkWidth = (int) dmarkWidth;
			int imarkHeight = (int) dmarkHeight;
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));

			// 6、水印图片的位置
			int x = (srcWidth - imarkWidth) / 2;
			int y = (srcHeight - imarkHeight) / 2;

			g.drawImage(img, x, y, imarkWidth, imarkHeight, null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
			
			// 7、释放资源
			g.dispose();
			
			// 8、生成图片
			out = new FileOutputStream(desPic);
			ImageIO.write(buffImg, "JPG", out);
			logger.debug("图片完成压缩并添加水印图片");
			return true;
		} catch (IOException e) {
			logger.warn("图片压缩或添加水印失败:" + e.getMessage());
			return false;
		}
	}
	
	/**
	 * 按比例压缩图片并添加水印
	 * 
	 * @param in
	 * 				inputstream
	 * @param scale
	 * 				缩放比例
	 * @param watermark
	 * 				水印图片
	 * @param desPic
	 * 				目标图片
	 * @return
	 */
	public static boolean compressAndAddWatermark(InputStream in, float scale, String watermark, String desPic) {
		logger.debug("按比例压缩图片并添加水印");
		try {
			if(in == null || in.available() == Constant.ZERO || StringUtils.isEmpty(desPic)) {
				logger.warn("压缩&添加水印失败:(");
				return false;
			}
			if(desPic.indexOf(".") == -1) {
				logger.warn("压缩&添加水印失败:目标图片后缀名为空:(");
				return false;
			}
			int kbSize = in.available() / Constant.ONE_KB;	//kb数
			String prefixPic = desPic.substring(0, desPic.lastIndexOf("."));	//图片前缀
			String ext = desPic.substring(desPic.lastIndexOf(".") + 1).toLowerCase();
			//输出质量
			float quality = 0;
			
			//jpg或jpeg
			if(Constant.JPG_EXT.equals(ext) || Constant.JPEG_EXT.equals(ext)) {
				if(kbSize <= 200) {
					quality = 1.0f;
				} else if(kbSize > 200 && kbSize <= 400) {
					quality = 0.5f;
				} else if(kbSize > 400 && kbSize <= 800) {
					quality = 0.25f;
				} else if(kbSize > 800 && kbSize <= 2048) {
					quality = 0.1f;
				} else {
					quality = (float) Constant.DEFAULT_COMPRESS_KB_SIZE / kbSize;
				}
			} else {
				//其他图片格式均转为jpg
				desPic = prefixPic + ".jpg";
				if(kbSize <= 200) {
					quality = 1.0f;
				} else if(kbSize > 200 && kbSize <= 1024) {
					quality = 0.5f;
				} else if(kbSize > 1024 && kbSize <= 3 * 1024) {
					quality = 0.25f;
				} else {
					quality = 0.1f;
				}
			}
			Thumbnails.of(in).scale(scale).imageType(BufferedImage.TYPE_INT_ARGB)
					.watermark(Positions.CENTER, ImageIO.read(new File(watermark)), Constant.DEFAULT_OPACITY)
					.outputQuality(quality).toFile(desPic);
			return true;
		} catch (IOException e) {
			logger.warn("图片压缩&添加水印失败:" + e.getMessage());
			return false;
		}
	}
	
	/**
	 * 其他图片后缀名转成jpg
	 * @param picName
	 * 			图片名称	
	 * @return
	 */
	public static String otherPicExt2Jpg(String picName) {
		if(StringUtils.isEmpty(picName) || picName.indexOf(".") == -1) {
			logger.warn("其他图片后缀名转成jpg失败:图片名称或后缀名为空:(");
			return null;
		}
		String prefixPic = picName.substring(0, picName.lastIndexOf("."));
		//获取后缀名并转为小写
		String ext = picName.substring(picName.lastIndexOf(".") + 1).toLowerCase();
		//jpeg,jpg
		if(!Constant.JPEG_EXT.equals(ext) && !Constant.JPG_EXT.equals(ext)) {
			picName = prefixPic + ".jpg";
		}
		return picName;
	}
	
	/**
	 * 根据认证排序值获取认证身份
	 * @param authSort
	 * 				身份认证排序
	 * @return
	 */
	public static String getAuthName(Integer authSort) {
		String authName = null;
		switch (authSort) {
		case 1:
			authName = "梦想教师";
			break;
		case 2:
			authName = "志愿者";
			break;
		case 3:
			authName = "基金会员工";
			break;
		case 4:
			authName = "教练计划";
			break;
		case 5:
			authName = "学生计划";
			break;
		case 6:
			authName = "去远方—教师";
			break;
		case 7:
			authName = "去远方—学生";
			break;
		case 8:
			authName = "去远方—出行志愿者";
			break;
		case 9:
			authName = "去远方—评审志愿者";
			break;
		case 10:
			authName = "城市版社区";
			break;
		case 11:
			authName = "教练计划-社会志愿者";
			break;
		case 12:
			authName = "教练计划-学生志愿者";
			break;
		case 13:
			authName = "教练计划-领队";
			break;
		case 14:
			authName = "教练计划-讲师";
			break;
		case 15:
			authName = "运动梦想课";
			break;
		case 16:
			authName = "校长训练营";
			break;
		case 20:
			authName = "乡镇版社区";
			break;
		case 101:
			authName = "企业";
			break;
		case 102:
			authName = "政府";
			break;
		case 103:
			authName = "社会组织";
			break;
		case 104:
			authName = "专项基金";
			break;
		case 105:
			authName = "公益团队";
			break;
		default:
			authName = null;
			break;
		}
		return authName;
	}
	
	/**
	 * 根据认证角色排序值获取认证角色id
	 * @param sort	认证角色排序值
	 * @return
	 */
	public static String getVerifyRleIdBySort(Integer sort) {
		if(sort == null) {
			logger.warn("获取认证角色id失败:认证角色排序值为空:(");
			return null;
		}
		return roleSortMap.get(sort);
	}
	/**
	 * 本地图片转换Base64的方法
	 *
	 * @param imgPath     
	 */

	public static String ImageToBase64(String imgPath) {
		if(StringUtils.isEmpty(imgPath)||StringUtils.isEmpty(imgPath.trim())) {
			return "";
		}
	    byte[] data = null;
	    // 读取图片字节数组
	    try {
	        InputStream in = new FileInputStream(imgPath);
	        data = new byte[in.available()];
	        in.read(data);
	        in.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    // 对字节数组Base64编码
	    BASE64Encoder encoder = new BASE64Encoder();
	    // 返回Base64编码过的字节数组字符串
	    return encoder.encode(Objects.requireNonNull(data));
	}
 
	 
	//链接url下载图片 
	//目录需要先创建
    public static boolean downloadPicture(String urlString,String imgPath) {
        URL url = null;
        try {
            url = new URL(urlString);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
 
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imgPath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
 
            byte[] buffer = new byte[1024];
            int length;
 
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            return true;
        } catch (MalformedURLException e) {
        	return false;
        } catch (IOException e) {
        	return false;
        }
    }
    
    /**
     *	 判断是否为整数
     * @param str
     * @return
     */
    public static boolean isInteger(String str) {
    	//空字符串的话 下面就会返回true,因此要先加这个条件
    	//两边如果有空白 也认为不是个数字
    	if(StringUtils.isEmpty(str)||StringUtils.isEmpty(str.trim())) {
    		return false;
    	}
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
    }
    
    /**url参数转为jsonobject
     * 例:a=a1&b=b1&c=c1
     * @param paramStr
     * @return
     */
    public static JSONObject getJsonObjectByQueueUrl(String paramStr) {
    	String[] params = paramStr.split("&");
    	JSONObject jsonObject = new JSONObject();
    	int length = params.length;
    	for (int i = 0; i < length; i++) {
			String[] param = params[i].split("=");
			if(param.length >= 2) {
				String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                jsonObject.put(key, value);
			} else {				
				return null;
			}
		}
    	return jsonObject;
    }
    /**
     *	获取参数值
     * @param url
     * @param name
     * @return
     */
    public static String getParam(String url, String name) {
    	try {
    		 String params = url.substring(url.indexOf("?") + 1, url.length());
    	     Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
    	     return split.get(name);
		} catch (Exception e) {
			return null;
		}
    }
    
    /**
     * 读取配置文件配置项的值
     * @param file	配置文件
     * @param property	配置项
     * @return
     */
    public static String readProperty(String file, String property) {
    	Properties properties = new Properties();
	    // 使用ClassLoader加载properties配置文件生成对应的输入流
	    InputStream in = Utils.class.getClassLoader().getResourceAsStream(file);
	    // 使用properties对象加载输入流
	    try {
			properties.load(in);
			//获取key对应的value值
			return properties.getProperty(property);
		} catch (IOException e) {
			logger.warn("读取配置文件配置项失败:(");
			return null;
		}
    }
    
    
    public static Utils instance = new Utils();
    
    public static CmsClient client;
    static{
    	 String secretId = "AKIDFEwMVPwe2uTlkSe95j6ARQ7XdSy1O36r";
    	 String secretKey = "buRihPhhPREiuoQkX3HDi01JI0RaRr1t";
    	 Credential cred = new Credential(secretId, secretKey);
    	 client = new CmsClient(cred, "ap-beijing");
    }
    /** 
     *	 验证 文本内容 合法性
     * instance 调用
     */
    public String verifyContent(String content) throws ADreamServiceException, TencentCloudSDKException{
         // 通过 client 对象调用想要访问的接口，需要传入请求对象
         String base64 = new BASE64Encoder().encode(content.getBytes());
         Map<String,String> param = new HashMap<>();
         param.put("Content", base64);
         //String payload = "{\"Content\":\""+ base64 +"\"}";
         String payload = JSON.toJSONString(param);
         String resp = client.call("TextModeration", payload);
         return resp;
      
    }
    /**
     * 	 验证 图片内容 合法性
     * @param imgBase64
     * @return
     * @throws ADreamServiceException
     * @throws TencentCloudSDKException
     */
    public String  verifyFileContent(String imgBase64) throws ADreamServiceException, TencentCloudSDKException{
       Map<String,String> param = new HashMap<>();
       param.put("FileContent", imgBase64);
       String FileContent = JSON.toJSONString(param);
       String resp = client.call("ImageModeration", FileContent);
       return resp;
    }
    
    /**
     * 获取客户端的IP地址
     * 注意本地测试访问项目地址时，浏览器请求不要用 localhost，请用本机IP；否则，取不到 IP
     *
     * @return String 真实IP地址
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String headerName = "x-forwarded-for";
        String ip = request.getHeader(headerName);
        if (null != ip && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个IP才是真实IP,它们按照英文逗号','分割
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (checkIp(ip)) {
            headerName = "Proxy-Client-IP";
            ip = request.getHeader(headerName);
        }
        if (checkIp(ip)) {
            headerName = "WL-Proxy-Client-IP";
            ip = request.getHeader(headerName);
        }
        if (checkIp(ip)) {
            headerName = "HTTP_CLIENT_IP";
            ip = request.getHeader(headerName);
        }
        if (checkIp(ip)) {
            headerName = "HTTP_X_FORWARDED_FOR";
            ip = request.getHeader(headerName);
        }
        if (checkIp(ip)) {
            headerName = "X-Real-IP";
            ip = request.getHeader(headerName);
        }
        if (checkIp(ip)) {
            headerName = "remote addr";
            ip = request.getRemoteAddr();
            // 127.0.0.1 ipv4, 0:0:0:0:0:0:0:1 ipv6
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        return ip;
    }
    
    private static boolean checkIp(String ip) {
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            return true;
        }
        return false;
    }
}